package org.example.weboj.util;

import io.jsonwebtoken.*;
import org.example.weboj.entity.User;
import org.springframework.stereotype.Component;
import java.util.Date;

@Component
public class JwtUtils {
    private final String secret = "secretKey123";
    private final long expiration = 1000 * 60 * 60; // 1小时

    public String generateToken(User user) {
        return Jwts.builder()
                .setSubject(user.getId().toString())
                .claim("username", user.getUsername())
                .claim("role", user.getRole())
                .setExpiration(new Date(System.currentTimeMillis() + expiration))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    public String getUsernameFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody().get("username", String.class);
    }

    public String getRoleFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token)
                .getBody().get("role", String.class);
    }

    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(secret).parseClaimsJws(token);
            return true;
        } catch (ExpiredJwtException e) {
            System.out.println("Token 已过期");
        } catch (UnsupportedJwtException e) {
            System.out.println("不支持的 Token");
        } catch (MalformedJwtException e) {
            System.out.println("无效的 Token 格式");
        } catch (SignatureException e) {
            System.out.println("签名不匹配");
        } catch (IllegalArgumentException e) {
            System.out.println("参数为空");
        }
        return false;
    }
}
